package com.yungu.swift.lbs.trace.google;


import com.yungu.swift.utils.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


/**
 * 谷歌请求工具类
 *
 * @author Zerrion
 * @date 2018/2/26
 */
public class GoogleRequestUtils {
    private static final Logger logger = LoggerFactory.getLogger(GoogleRequestUtils.class);
    private static final Integer GOOGLE_API_TIMEOUT_MILLISECOND = 3000;

    /**
     * 执行get请求
     *
     * @param url 谷歌请求地址
     * @return BigDecimal
     * @author Zerrion
     * @date 2018/1/9
     */
    public static Map<String, Object> get(String url, String key) {
        Map<String, Object> resultMap = new HashMap<>(2);
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;

        //拼接请求key
        url += ("&key=" + key);
        try {
            client = HttpUtils.createDefaultClient(url);
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(RequestConfig.copy(RequestConfig.DEFAULT)
                    .setConnectionRequestTimeout(GOOGLE_API_TIMEOUT_MILLISECOND)
                    .setConnectTimeout(GOOGLE_API_TIMEOUT_MILLISECOND)
                    .setSocketTimeout(GOOGLE_API_TIMEOUT_MILLISECOND)
                    .build());

            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
            logger.info("send HTTP GET request to [" + url + "]");
            response = client.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            resultMap.put("status", response.getStatusLine().getStatusCode());
            resultMap.put("result", EntityUtils.toString(httpEntity, StandardCharsets.UTF_8));
            EntityUtils.consume(httpEntity);
        } catch (SocketException e) {
            logger.info(e.getMessage());
            resultMap.put("status", -1);
            resultMap.put("result", e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
            resultMap.put("status", -1);
            resultMap.put("result", e.getMessage());
        } finally {
            HttpUtils.close(client, response);
        }
        return resultMap;
    }

}
